package com.jeecg.xiaozhi.wxuser.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jeecg.xiaozhi.wxuser.entity.WxUserEntity;
import com.jeecg.xiaozhi.wxuser.service.WxUserServiceI;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @Title: Controller
 * @Description: 微信用户
 * @author onlineGenerator
 * @date 2018-08-24 21:35:49
 * @version V1.0
 *
 */
@Api(value = "WxUser", description = "微信用户", tags = "wxUserController")
@Controller
@RequestMapping("/wxUserController")
public class WxUserController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(WxUserController.class);

	@Autowired
	private WxUserServiceI wxUserService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;

	/**
	 * 微信用户列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/jeecg/xiaozhi.wxuser/wxUserList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(WxUserEntity wxUser, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(WxUserEntity.class, dataGrid);
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, wxUser, request.getParameterMap());
		cq.add();
		this.wxUserService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除微信用户
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(WxUserEntity wxUser, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		wxUser = systemService.getEntity(WxUserEntity.class, wxUser.getId());
		message = "微信用户删除成功";
		try {
			wxUserService.delete(wxUser);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "微信用户删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除微信用户
	 * 
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "微信用户删除成功";
		try {
			for (String id : ids.split(",")) {
				WxUserEntity wxUser = systemService.getEntity(WxUserEntity.class, Integer.parseInt(id));
				wxUserService.delete(wxUser);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "微信用户删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加微信用户
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(WxUserEntity wxUser, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "微信用户添加成功";
		try {
			wxUserService.save(wxUser);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "微信用户添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新微信用户
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(WxUserEntity wxUser, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "微信用户更新成功";
		WxUserEntity t = wxUserService.get(WxUserEntity.class, wxUser.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(wxUser, t);
			wxUserService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "微信用户更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "wxUserController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(WxUserEntity wxUser, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(WxUserEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, wxUser, request.getParameterMap());
		List<WxUserEntity> wxUsers = this.wxUserService.getListByCriteriaQuery(cq, false);
		modelMap.put(NormalExcelConstants.FILE_NAME, "微信用户");
		modelMap.put(NormalExcelConstants.CLASS, WxUserEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,
				new ExportParams("微信用户列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, wxUsers);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(WxUserEntity wxUser, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid, ModelMap modelMap) {
		modelMap.put(NormalExcelConstants.FILE_NAME, "微信用户");
		modelMap.put(NormalExcelConstants.CLASS, WxUserEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,
				new ExportParams("微信用户列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<WxUserEntity> listWxUserEntitys = ExcelImportUtil.importExcel(file.getInputStream(),
						WxUserEntity.class, params);
				for (WxUserEntity wxUser : listWxUserEntitys) {
					wxUserService.save(wxUser);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "微信用户列表信息", produces = "application/json", httpMethod = "GET")
	public ResponseMessage<List<WxUserEntity>> list() {
		List<WxUserEntity> listWxUsers = wxUserService.getList(WxUserEntity.class);
		return Result.success(listWxUsers);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "根据ID获取微信用户信息", notes = "根据ID获取微信用户信息", httpMethod = "GET", produces = "application/json")
	public ResponseMessage<?> get(@ApiParam(required = true, name = "id", value = "ID") @PathVariable("id") String id) {
		WxUserEntity task = wxUserService.get(WxUserEntity.class, Integer.valueOf(id));
		if (task == null) {
			return Result.error("根据ID获取微信用户信息为空");
		}
		return Result.success(task);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "创建微信用户")
	public ResponseMessage<?> create(@ApiParam(name = "微信用户对象") @RequestBody WxUserEntity wxUser,
			UriComponentsBuilder uriBuilder) {
		// 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<WxUserEntity>> failures = validator.validate(wxUser);
		if (!failures.isEmpty()) {
			return Result.error(JSON.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		// 保存
		try {
			wxUserService.save(wxUser);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("微信用户信息保存失败");
		}
		return Result.success(wxUser);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "更新微信用户", notes = "更新微信用户")
	public ResponseMessage<?> update(@ApiParam(name = "微信用户对象") @RequestBody WxUserEntity wxUser) {
		// 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<WxUserEntity>> failures = validator.validate(wxUser);
		if (!failures.isEmpty()) {
			return Result.error(JSON.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		// 保存
		try {
			wxUserService.saveOrUpdate(wxUser);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("更新微信用户信息失败");
		}

		// 按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success("更新微信用户信息成功");
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value = "删除微信用户")
	public ResponseMessage<?> delete(
			@ApiParam(name = "id", value = "ID", required = true) @PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			wxUserService.deleteEntityById(WxUserEntity.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("微信用户删除失败");
		}

		return Result.success();
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "微信用户列表信息", produces = "application/json;charset=UTF-8", httpMethod = "GET")
	public ResponseMessage<WxUserEntity> login(WxUserEntity wxUserEntity, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// Properties properties = new Properties();
		// 使用ClassLoader加载properties配置文件生成对应的输入流
		// FileInputStream in = new FileInputStream("weixin_config.propertise");
		// InputStream in =
		// this.getClass().getClassLoader().getResourceAsStream("weixin_config.propertise");
		// 使用properties对象加载输入流
		// properties.load(in);
		// 获取key对应的value值
		// String AppID = properties.getProperty("AppID");
		// String AppSecret = properties.getProperty("AppSecret");
		// String
		// url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AppID+"&secret="+AppSecret+"&code="+wxUserEntity.getCode()+"&grant_type=authorization_code";
		// String openid=JwtHttpUtil.SSLhttpRequest(url, "GET", null);
		// System.out.println("获取微信小程序openid666888："+openid);
		// System.out.println("获取微信小程序openid6666："+testQ(AppID, AppSecret,
		// wxUserEntity));
		List<WxUserEntity> list = wxUserService.findByProperty(WxUserEntity.class, "openid", wxUserEntity.getOpenid());
		if (list != null && list.size() > 0) {
			// wxUserEntity.setId(list.get(0).getId());
			WxUserEntity wxuser = list.get(0);
			wxuser.setAvatarUrl(wxUserEntity.getAvatarUrl());
			wxuser.setNickName(wxUserEntity.getNickName());
			wxuser.setGender(wxUserEntity.getGender());
			wxuser.setLanguage(wxUserEntity.getLanguage());
			wxuser.setCity(wxUserEntity.getCity());
			wxuser.setProvince(wxUserEntity.getProvince());
			wxuser.setCountry(wxUserEntity.getCountry());
			wxUserService.saveOrUpdate(wxuser);
			return Result.success(wxuser);
		} else {
			try {
				wxUserService.save(wxUserEntity);
				list.add(wxUserEntity);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// List<WxUserEntity> listWxUsers = wxUserService.getList(WxUserEntity.class);
		return Result.success(list.get(0));
	}

	public String testQ(String AppID, String AppSecret, WxUserEntity wxUserEntity) {
		// StringBuilder url = new StringBuilder();
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppID + "&secret=" + AppSecret
				+ "&code=" + wxUserEntity.getCode() + "&grant_type=authorization_code";
		// url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
		// url.append("appid=").append(this.wxMpService.getWxMpConfigStorage().getAppId());
		// url.append("&secret=").append(this.wxMpService.getWxMpConfigStorage().getSecret());
		// url.append("&code=").append(code);
		// url.append("&grant_type=authorization_code");
		HttpClient httpclient = new DefaultHttpClient();
		// httpclient = this.wrapClient(httpclient);

		BufferedReader in = null;
		String content = null;
		try {
			HttpClient client = getSecuredHttpClient(httpclient);
			// 实例化HTTP方法
			HttpGet request = new HttpGet();
			request.setURI(new URI(url.toString()));
			HttpResponse response = client.execute(request);

			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			content = sb.toString();
			System.out.println(content);
			Gson gson = new GsonBuilder().create();
			JsonParser jsonParser = new JsonParser();
			JsonObject jsonObject = jsonParser.parse(content).getAsJsonObject();
			String openid = jsonObject.get("openid").getAsString();
			return openid;
		} catch (Exception e) {
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	/**
	 * 重新包装httpclient对象，忽略证书验证
	 * 
	 * @param httpClient
	 * @return
	 * @author:Administrator
	 * @date:2014-9-2
	 */
	private static DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) {
		final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				@Override
				public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
						throws CertificateException {
					// TODO Auto-generated method stub

				}

				@Override
				public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
						throws CertificateException {
					// TODO Auto-generated method stub

				}

				@Override
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}
			};
			ctx.init(null, new javax.net.ssl.TrustManager[] { tm }, new SecureRandom());
			SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = httpClient.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));
			return new DefaultHttpClient(ccm, httpClient.getParams());
		} catch (Exception e) {
			System.out.println("=====:=====");
			e.printStackTrace();
		}
		return null;
	}
}
